var server = require('../server')
var db = require('../../db/connect')
var jsonres = require('../../libs/jsonres')
var request = require('request')
var config = require('../../config')

server.post('/api/sync',function(req,res) {
    var p = req.body.platform;
    var u = req.session.u;
    var user = req.body.user;
    var pwd = req.body.pwd;
    var appnames = {
        '德扑圈': 'com.texaspoker.moment',
        'KK扑克': 'com.kkpoker.moment',
    }

    // TODO: 等小机器人实现自动抓取多个牌局 则一次只允许单个任务!

    // db.find('tasks',{user: user, platform: p, mobile: u, finished: false}, function(err, result){
    //     if (result.length > 0) {
    //         res.send(jsonres(-1,'还有未同步完成的数据',null))
    //         return
    //     } else {
            request({
                url: config.dispatcher_host + '/getque',
                json:true,
                method: 'POST',
                body: {
                    appname: appnames[p],
                    username: user,
                    pwd: pwd,
                    mobile: u
                }
            },function(err,httpResponse,body) {
                if (!err) {
                    db.insert('tasks',{mobile: u, platform: p, user: user,taskId: httpResponse.body, finished: false, time: new Date(Date.now() + (8 * 60 * 60 * 1000)), title: '',alliance: '', master:''})
                    res.send(jsonres(200,'success',httpResponse.body))
                } else {
                    res.send(jsonres(-1,'发送同步请求失败',err))
                }
            })
    //     }
    // })
})

server.get('/api/checktask',function(req, res) {
    var taskid = req.query.taskid;
    request({
        url: config.dispatcher_host + '/gettask?task=' + taskid,
        method: 'get',
    },function(err,httpResponse,body) {
        res.send(jsonres(200,'success',body))
    })
})

server.get('/api/getuid',function(req, res) {
    var platform = req.query.platform;
    var mobile = req.query.mobile;
    var uid = '';
    db.find('accounts',{platform: platform, user: mobile},function(err,result){
        if (result.length > 0) {
            uid = result[0].userid;
            if (uid && uid.length > 0) {
                return res.send(jsonres(200,'success',uid))
            }
            return res.send(jsonres(-1,'not found any userid',null))
        }
        return res.send(jsonres(-1,'not found any userid',null))
    })
})

server.get('/api/rowdata',function(req, res) {
    var id = req.query.id;
    request({
        url: config.dispatcher_host + '/getrowdata?id=' + id,
        method: 'get',
    },function(err,httpResponse,body) {
        if (!!!err) {
            if (body !== 'fail') {
                res.send(jsonres(200,'success',JSON.parse(body)))
            } else {
                res.send(jsonres(-1,'not found row data',null))
            }
        } else {
            res.send(jsonres(-1,'fail',null))
        }
    })
})
